package com.supcon.tinyportal.util;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.PageContext;

public class RequestUtil {

    public static boolean isPostback(HttpServletRequest request) {
        return request.getAttribute(Constants.PORTLET_EVENT) != null;
    }

    public static boolean isAjax(HttpServletRequest request) {
        return request.getParameter(Constants.AJAX_ENABLE) != null;
    }

    public static String getFullAddress(HttpServletRequest request) {

        HttpServletRequest tmpRequest = request;

        if (request instanceof HttpServletRequestWrapper) {
            while (tmpRequest instanceof HttpServletRequestWrapper) {
                tmpRequest = (HttpServletRequest) ((HttpServletRequestWrapper)
                        tmpRequest).getRequest();
            }
        }

        String address = tmpRequest.getRequestURL().toString();
        String queryString = tmpRequest.getQueryString();
        return (queryString != null && queryString.length() > 0) ?
               (address += "?" + queryString) : address;
    }

    public static StringBuffer createServerUriStringBuffer(String scheme,
            String server, int port, String uri) {
        StringBuffer serverUri = createServerStringBuffer(scheme,server,port);
        serverUri.append(uri);
        return serverUri;
    }

    public static StringBuffer createServerStringBuffer(String scheme,
            String server, int port) {

        StringBuffer url = new StringBuffer();
        if (port < 0) {
            port = 80; // Work around java.net.URL bug
        }
        url.append(scheme);
        url.append("://");
        url.append(server);
        if ((scheme.equals("http") && (port != 80)) || (scheme.equals("https") && (port != 443))) {
            url.append(':');
            url.append(port);
        }
        return url;
    }

    public static Object classInstance(String className)
            throws ClassNotFoundException, InstantiationException, IllegalAccessException {

        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

        return classLoader.loadClass(className).newInstance();

    }

    public static void updatePortletInfo(PageContext pageContext) {
        HttpServletRequest request = (HttpServletRequest) (pageContext.getRequest());
        HttpServletResponse response = (HttpServletResponse) (pageContext.getResponse());

        PortletInfoHolder portletInfo = getPortletInfo(request);

        if (isPostback(request) || RequestUtil.isAjax(request)) {
            if (isAjax(request)) {
                response.setContentType("text/xml");
            }
        } else {
            String addr = getFullAddress(request);
            portletInfo.setPageAddress(addr);
        }

        String postbackReloadAddress = request.getParameter(Constants.RELOAD_ADDR);
        if (postbackReloadAddress != null) {
        	portletInfo.setPageAddress(postbackReloadAddress);
        }

        String compURI = (String) request.getAttribute("javax.servlet.include.request_uri");
        if (compURI == null || compURI.length() == 0) {
            compURI = request.getRequestURI();
        }
        String portletAddress = createServerUriStringBuffer(request.getScheme(),
            request.getServerName(), request.getServerPort(), compURI).toString();
        portletInfo.setPortletAddress(portletAddress);

        pageContext.setAttribute(Constants.RELOAD_ADDR, portletInfo.getPageAddress());
        pageContext.setAttribute(Constants.PORTLET_ADDR, portletInfo.getPortletAddress());

        request.setAttribute(Constants.RELOAD_ADDR, portletInfo.getPageAddress());
        request.setAttribute(Constants.PORTLET_ADDR, portletInfo.getPortletAddress());
    }

    public static PortletInfoHolder getPortletInfo(HttpServletRequest request) {
        HttpSession session = request.getSession();

        synchronized(session) {
        	PortletInfoHolder portletInfo = (PortletInfoHolder) session.getAttribute(Constants.PORTLET_INFO_KEY);
            if (portletInfo == null) {
            	portletInfo = new PortletInfoHolder();
            	portletInfo.setStateMap(new HashMap<Object,Object>());
                session.setAttribute(Constants.PORTLET_INFO_KEY, portletInfo);
            }
            return portletInfo;
        }
    }

    public static String getReloadAddress(PageContext pageContext) {
        return (String) pageContext.findAttribute(Constants.RELOAD_ADDR);
    }

    public static String getPortletAddress(PageContext pageContext) {
        return (String) pageContext.findAttribute(Constants.PORTLET_ADDR);
    }

    public static void removeScopedValue(PageContext pageContext, String varname) {
        pageContext.removeAttribute(varname);
        pageContext.getRequest().removeAttribute(varname);
        pageContext.getSession().removeAttribute(varname);
        pageContext.getServletContext().removeAttribute(varname);
    }

}
